package com.urea.system.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.urea.common.core.domain.entity.Customer;
import com.urea.common.core.domain.entity.SysRole;
import com.urea.common.core.domain.entity.SysUser;
import com.urea.common.exception.ServiceException;
import com.urea.common.utils.SecurityUtils;
import com.urea.system.domain.CustomerAccount;
import com.urea.system.domain.FleetUser;
import com.urea.system.domain.vo.FleetUserVo;
import com.urea.system.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.urea.system.mapper.FleetMapper;
import com.urea.system.domain.Fleet;

/**
 * 车队Service业务层处理
 * 
 * @author liuzd
 * @date 2023-08-01
 */
@Service
public class FleetServiceImpl extends ServiceImpl<FleetMapper, Fleet> implements IFleetService
{
    @Autowired
    private FleetMapper fleetMapper;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IFleetUserService fleetUserService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ICustomerAccountService customerAccountService;

    @Value("${ruoyi.password}")
    private String password;
    /**
     * 查询车队
     * 
     * @param id 车队主键
     * @return 车队
     */
    @Override
    public Fleet selectFleetById(Long id)
    {
        return fleetMapper.selectFleetById(id);
    }

    /**
     * 查询车队列表
     * 
     * @param fleet 车队
     * @return 车队
     */
    @Override
    public List<Fleet> selectFleetList(Fleet fleet)
    {
        return fleetMapper.selectFleetList(fleet);
    }

    /**
     * 新增车队
     * 
     * @param vo 车队
     */
    @Override
    public void insertFleet(FleetUserVo vo)
    {

        // 账号查询
        Customer customer = customerService.getOne(Wrappers.lambdaQuery(Customer.class).eq(Customer::getPhone,vo.getPhone()));
        if (Objects.isNull(customer)){
//            throw new ServiceException("用户信息为空!");
            Customer cus = new Customer();
            cus.setPhone(vo.getPhone());
            cus.setAccount(vo.getPhone());
            cus.setPassword(vo.getPhone());
            cus.setFleetName(vo.getFleetName());
            cus.setNickName(vo.getNickName());
            customerService.save(cus);
            // 创建账户信息
            CustomerAccount account = new CustomerAccount();
            account.setBalance(BigDecimal.ZERO);
            account.setCreatedTime(LocalDateTime.now());
            account.setCustomerId(cus.getId());
            customerAccountService.save(account);
        }else{
            // 检验唯一性
            FleetUser fleetUser = fleetUserService.getOne(Wrappers.lambdaQuery(FleetUser.class).eq(FleetUser::getUid, customer.getId()));
            if (Objects.nonNull(fleetUser)){
                throw new ServiceException("当前账号以绑定车队,请先联系队长解绑!");
            }
            // 更新车队信息到用户表
            customerService.update(Wrappers.lambdaUpdate(Customer.class)
                    .eq(Customer::getId,customer.getId()).set(Customer::getFleetName,vo.getFleetName()));
        }
        // 新建车队信息
        Fleet fleet = new Fleet();
        fleet.setFleetName(vo.getFleetName());
        fleet.setRemark(vo.getRemark());
        this.save(fleet);
        // 车队用户关系 标识队长
        FleetUser insertUser = new FleetUser();
        insertUser.setFleetId(fleet.getId());
        insertUser.setIsMaster("1");
        insertUser.setUid(customer.getId());
        fleetUserService.save(insertUser);
        // 创建队长的后台账号
        SysUser param = new SysUser();
        param.setPhonenumber(vo.getPhone());
        List<SysUser> sysUsers = sysUserService.queryUserList(param);
        if (CollectionUtil.isNotEmpty(sysUsers)){
            return;
        }
        param.setUserName(vo.getPhone());
        param.setNickName(vo.getPhone());
        param.setUserType("03");
        param.setPassword(SecurityUtils.encryptPassword(password));
        // 车队角色
        List<SysRole> sysRoles = roleService.selectRoleAll();
        Optional<SysRole> first = sysRoles.stream().filter(s -> "fleet".equals(s.getRoleKey())).findFirst();
        if (first.isPresent()){
            Long [] roles = {first.get().getRoleId()};
            param.setRoleIds(roles);
        }
        sysUserService.insertUser(param);
    }

    /**
     * 修改车队
     * 
     * @param fleet 车队
     * @return 结果
     */
    @Override
    public int updateFleet(Fleet fleet)
    {
        // 去修用户里的车队信息
        List<FleetUser> list = fleetUserService.list(Wrappers.lambdaQuery(FleetUser.class).eq(FleetUser::getFleetId, fleet.getId()));
        if (CollectionUtils.isNotEmpty(list)){
            List<Long> uids = list.stream().map(FleetUser::getUid).collect(Collectors.toList());
            customerService.update(null,Wrappers.lambdaUpdate(Customer.class)
                    .in(Customer::getId,uids).set(Customer::getFleetName,fleet.getFleetName()));
        }
        return fleetMapper.updateFleet(fleet);
    }

    /**
     * 批量删除车队
     * 
     * @param ids 需要删除的车队主键
     * @return 结果
     */
    @Override
    public int deleteFleetByIds(Long[] ids)
    {
        return fleetMapper.deleteFleetByIds(ids);
    }

    /**
     * 删除车队信息
     * 
     * @param id 车队主键
     * @return 结果
     */
    @Override
    public int deleteFleetById(Long id)
    {
        return fleetMapper.deleteFleetById(id);
    }

    /**
     * 获取所有车队信息
     *
     * @return 车队信息
     */
    @Override
    public List<Fleet> queryFleetList() {
        return this.list();
    }
}
